<template>
  <div class="form">
    <el-form
      :model="form"
      ref="formRef"
      :rules="rule"
      label-position="top"
      label-width="auto"
    >
      <el-form-item label="设置类型" prop="tagRadio">
        <el-radio-group v-model="form.tagRadio">
          <el-radio label="0">单标签判断</el-radio>
          <el-radio label="1">多标签判断</el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="time-class">
        <el-form-item label="选择标签" prop="tagKey">
          <!-- <el-select
            v-model="form.tagKeyS"
            filterable
            placeholder="请选择"
            @change="getPropertyType"
          >
            <el-option
              v-for="item in messageData.tagList"
              :key="item.propertyKey"
              :label="item.propertyName"
              :value="item.propertyKey"
            ></el-option>
          </el-select> -->
          <ScSelector
            v-model="form.tagKeySID"
            type="userTags"
            @change-selected="getPropertyType"
          >
            <template #expand-pop="{ data }">
              <div v-if="data" class="detail-container">
                <h3>
                  {{ data.info.propertyName }}
                  <el-tag>{{
                    labelType[data.info.propertyType.toString()]
                  }}</el-tag>
                </h3>
                <div class="detail-text_line">
                  标签CODE：
                  {{ data.info.propertyKey || "" }}
                </div>
                <div class="detail-text_line">
                  所属机构：
                  {{ data.info.insName }}
                </div>
                <div>
                  所属分组：
                  {{ data.info.groupName || "全部" }}
                </div>
                <div>
                  备注：
                  {{ data.info.remark || "暂无" }}
                </div>
              </div>
            </template>
          </ScSelector>

          <!-- <el-cascader v-else v-model="form.tagKey" @input="filterTagFun" filterable :props="casderProps" /> -->
        </el-form-item>
        <el-form-item class="operationType" v-if="form.tagRadio == '1'">
          <el-select
            v-model="form.operationType"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in messageData.operatorList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>

      <el-form-item v-if="form.tagRadio == '1'" prop="tagKey">
        <!-- <el-select
          v-model="form.tagKeyE"
          filterable
          placeholder="请选择"
          @change="tagKeyEChange"
        >
          <el-option
            v-for="item in messageData.tagList"
            :key="item.propertyKey"
            :label="item.propertyName"
            :value="item.propertyKey"
          ></el-option>
        </el-select> -->
        <ScSelector
          v-model="form.tagKeyEID"
          type="userTags"
          @change-selected="tagKeyEChange"
        >
          <template #expand-pop="{ data }">
            <div v-if="data" class="detail-container">
              <h3>
                {{ data.info.propertyName }}
                <el-tag>{{
                  labelType[data.info.propertyType.toString()]
                }}</el-tag>
              </h3>
              <div class="detail-text_line">
                标签CODE：
                {{ data.info.propertyKey || "" }}
              </div>
              <div class="detail-text_line">
                所属机构：
                {{ data.info.insName }}
              </div>
              <div class="detail-text_line">
                所属分组：
                {{ data.info.groupName || "全部" }}
              </div>
            </div>
          </template>
        </ScSelector>
        <!-- <el-cascader v-else v-model="form.tagKey" @input="filterTagFun" filterable :props="casderProps" /> -->
      </el-form-item>

      <el-form-item v-show="form.tagKeyS" label="连接关系" prop="connRela">
        <el-select v-model="form.connRela" placeholder="请选择">
          <el-option
            v-for="item in tagConnection"
            :value="item.id"
            :label="item.name"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <div v-if="form.connRela !== '!_null' && form.connRela !== '_null'">
        <!-- 数字 -->
        <div v-if="form.propertyType == 0">
          <el-form-item label="判断值" prop="radio">
            <el-input-number
              v-model="form.value"
              :min="1"
              :max="99999999"
              controls-position="right"
            />
          </el-form-item>
        </div>
        <!-- 字符串 -->
        <div v-if="form.propertyType == 1">
          <el-form-item label="判断值" prop="radio">
            <el-input
              v-model="form.value"
              maxlength="100"
              placeholder="请输入"
              show-word-limit
            />
          </el-form-item>
        </div>
        <!-- 枚举 -->
        <div v-if="form.propertyType == 4">
          <el-form-item label="判断值" prop="radio">
            <el-select v-model="form.value" placeholder="请选择">
              <el-option
                v-for="item in messageData.enumerationList"
                :key="item.k"
                :label="item.v"
                :value="item.k"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- 布尔 -->
        <div v-if="form.propertyType == 5">
          <el-form-item label="判断值" prop="radio">
            <el-input-number
              v-model="form.value"
              :min="1"
              :max="99999999"
              controls-position="right"
            />
          </el-form-item>
        </div>

        <!-- 日期 -->
        <template v-if="form.propertyType == 3 || form.propertyType == 2">
          <el-form-item label="判断值" prop="radio">
            <el-radio-group
              v-model="form.timeValue"
              @change="tiemValueRadioChange"
            >
              <el-radio label="0">相对时间</el-radio>
              <el-radio label="1">固定时间 </el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="time-class" v-if="form.timeValue == '1'">
            <el-form-item prop="radio">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="请选择时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <div v-if="form.connRela == 'true'">_</div>
            <el-form-item v-if="form.connRela == 'true'" prop="radio">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="请选择时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="messageData.defaultTime"
              />
            </el-form-item>
          </div>
          <div class="time-class" v-if="form.timeValue == '0'">
            <el-form-item prop="radio">
              <el-input-number
                v-model="form.startTime"
                :min="0"
                :max="99999999"
                controls-position="right"
              />
            </el-form-item>
            <div v-if="form.connRela == 'true'">_</div>
            <el-form-item v-if="form.connRela == 'true'" prop="radio">
              <el-input-number
                v-model="form.endTime"
                :min="1"
                :max="99999999"
                controls-position="right"
              />
            </el-form-item>

            <el-form-item class="time-list" prop="radio">
              <el-select v-model="form.timeType" placeholder="请选择">
                <el-option
                  v-for="item in timeList"
                  :value="item.id"
                  :label="item.name"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </template>
      </div>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import ScSelector from "@/components/scSelector/ScSelector.vue";
import CustomerApi from "@/api/customerApi";
import type { FormInstance } from "element-plus";
import {
  deepClone,
  connectionsData,
  formatTimeStamp,
  formatTimeMs,
} from "@/utils";
import { labelType } from "@/config/dictionary";
// 获取分组列表
const getTagList = async () => {
  let rs = await CustomerApi.attributeList({
    currentPage: 1,
    showCount: -1,
  });
  if (rs.code === 200) {
    messageData.tagList = rs.payload;
  }
};
const timeList = ref([
  { name: "天", id: "1" },
  { name: "小时", id: "2" },
  { name: "分钟", id: "3" },
] as any);

//      * number(0,"数字类型"),
//      * string(1,"字符串类型"),
//      * time(2,"时间类型"),
//      * dateTime(3,"日期类型"),
//      * enumerate(4,"枚举类型")
//      * booleanTypes(5,"布尔类型")
const isThereAreData = ref([
  { name: "存在", id: "!_null" },
  { name: "不存在", id: "_null" },
]);
const connectionData = ref(deepClone(connectionsData()));
const tagConnection = ref([] as any);
const messageData = reactive({
  enumerationList: [] as any,
  tagList: [] as any,
  propertyType: 0,
  defaultTime: new Date(2000, 1, 1, 23, 59, 59),
  operatorList: [
    { name: "+", id: "+" },
    { name: "-", id: "-" },
    { name: "x", id: "*" },
    { name: "/", id: "/" },
  ],
});
const form = ref({
  operationType: "+",
  tagRadio: "0",
  tagKeyS: "",
  tagKeyE: "",
  tagKeySID: "",
  tagKeyEID: "",
  connRela: "",
  timeRadio: "0",
  value: "" as any,
  startTime: 0 as any,
  endTime: "" as any,
  timeType: "1",
  propertyType: 0,
  timeValue: "0",
  enumerateValue: "",
});

const tagKeyS = ref(),
  tagKeyE = ref();

const formRef = ref();

const props = defineProps({
  modelValue: {
    require: true,
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emits = defineEmits(["update:modelValue"]);
const tiemValueRadioChange = (val: any) => {
  if (val == 0) {
    form.value.startTime = 0;
    form.value.endTime = 1;
  } else {
    form.value.startTime = "";
    form.value.endTime = "";
  }
  tiemRadioChange(form.value.propertyType);
};
// 相对时间变化时修改为对应的关系
const tiemRadioChange = (val: any) => {
  // debugger
  tagConnection.value = [
    ...isThereAreData.value,
    ...connectionData.value[val].list,
  ];
  // if (val == 0) {
  //   tagConnection.value = xdTime.value;
  // } else {
  //   tagConnection.value = connectionData.value[form.value.propertyType].list;
  // }
};

const tagKeyEChange = (val: any) => {
  let startType = form.value.propertyType;
  let endType = val.selected[0].info.propertyType;
  form.value.tagKeyE = val.selected[0].id;
  if (startType !== endType) {
    ElMessage.warning("所选标签类型应保持一致");
    nextTick(() => {
      form.value.tagKeyE = "";
      form.value.tagKeyEID = "";
    });
  } else tagKeyE.value = val.selected[0].info;
};

// 设置连接关系
const getPropertyType = (val: any) => {
  form.value.tagKeyE = "";
  let item = val.selected[0].info;
  tagKeyS.value = item;
  if (item.propertyType == 4) {
    // 枚举类型把字符串转换成数组
    messageData.enumerationList = JSON.parse(item.enumerateValue);
    form.value.enumerateValue = item.enumerateValue;
  }
  form.value.propertyType = item.propertyType;
  form.value.connRela = "";
  form.value.tagKeyS = item.id;
  form.value.value = connectionData.value[form.value.propertyType].initialValue;
  tiemRadioChange(form.value.propertyType);
};
const stopWatch = watch(
  () => props.modelValue,
  (val: any) => {
    if (formRef.value) formRef.value.resetFields();
    form.value = Object.assign({}, form.value, val);
    nextTick(() => {
      stopWatch();
    });
  },
  {
    immediate: true,
  }
);

const rule = {
  // time: [{ required: true, message: "请选择时间区间", trigger: "change" }],
  // type: [{ required: true, message: "请选择时间类型", trigger: "change" }],
  // checkList: [{ validator: validateCheck }],
};

const save = () => {
  formRef.value.validate((valid: any) => {
    if (!valid) {
      return;
    }
  });
  return new Promise((resolve, reject) => {
    (formRef.value as FormInstance).validate((valid, invalidFields) => {
      if (valid) {
        let rule = {
          operationType: form.value.operationType,
          tagRadio: form.value.tagRadio,
          tagKeyS: form.value.tagKeyS,
          tagKeyE: form.value.tagKeyE,
          tagKeyEID: form.value.tagKeyEID,
          tagKeySID: form.value.tagKeySID,
          connRela: form.value.connRela,
          timeRadio: form.value.timeRadio,
          value: form.value.value,
          startTime: form.value.startTime,
          endTime: form.value.endTime,
          timeType: form.value.timeType,
          propertyType: form.value.propertyType,
          timeValue: form.value.timeValue,
          enumerateValue: form.value.enumerateValue,
          tagNameList: form.value.tagNameList||['',''],
          enumerationName: "",
          connRelaName: "",
          timeName: "" as any,
        };
        if (tagKeyS.value) rule.tagNameList[0] = tagKeyS.value.propertyName;
        if (tagKeyE.value) rule.tagNameList[1] = tagKeyE.value.propertyName;
        if (rule.tagRadio == 0) {
          rule.tagNameList = [rule.tagNameList[0]];
          rule.tagKeyEID = "";
          rule.tagKeyE = "";
        }

        // 提取连接符的选中名称
        rule.connRelaName = tagConnection.value.find(
          (item: any) => item.id == rule.connRela
        ).name;

        // 提取枚举的选中名称
        if (form.value.propertyType == 4) {
          rule.enumerationName = messageData.enumerationList.find(
            (item: any) => item.k == rule.value
          ).v;
        }

        if (rule.propertyType == 3 || rule.propertyType == 2) {
          if (rule.timeValue == "0") {
            rule.timeName = timeList.value.find(
              (item: any) => item.id == rule.timeType
            ).name;
          }
        }

        emits("update:modelValue", rule);
        resolve(true);
      } else {
        console.log(invalidFields);
        resolve(false);
      }
    });
  });
};
onBeforeMount(() => {
  // getTagList();
  tiemRadioChange(form.value.propertyType);
  if (form.value.enumerateValue) {
    messageData.enumerationList = JSON.parse(form.value.enumerateValue);
  }
});

defineExpose({ save });
</script>

<style lang="scss" scoped>
.time-class {
  display: flex;
  * {
    margin-right: 10px;
  }
}
.el-select,
.el-input {
  width: 440px;
}
.time-list .el-select {
  width: 208px;
}
.operationType {
  margin-top: 30px;
  width: 208px;
}

.detail-container {
  .detail-text_line {
    white-space: nowrap;
  }
}
</style>
